import heapq


class Solution:
    def furthestBuilding(self, heights: list, bricks: int, ladders: int) -> int:
        queue = []
        for i in range(1, len(heights)):
            diff = heights[i] - heights[i-1]
            if diff <= 0:
                continue
            heapq.heappush(queue, diff)
            if ladders < len(queue):
                bricks -= heapq.heappop(queue)
            if bricks < 0:
                return i-1

        return len(heights) - 1
